package com.lll.nettywebsocket.repository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.yeauty.pojo.Session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.lll.nettywebsocket.common.Constants.CID;

@Repository
@Slf4j
public class InMemoryWebsocketSessionRepositoryImpl implements WebsocketSessionRepository {

    private final Object lock = new Object();

    private ConcurrentHashMap<String, List<Session>> userSessions = new ConcurrentHashMap<>(256);

    @Override
    public void addSession(Session session) {
        String cid = session.getAttribute(CID);
        log.info("从session中获取的cid为:[{}]", cid);

        synchronized (lock) {
            if (userSessions.containsKey(cid)) {
                userSessions.get(cid).add(session);
            } else {
                List<Session> sessions = new ArrayList<>();
                sessions.add(session);
                userSessions.put(cid, sessions);
            }
        }
    }

    @Override
    public List<String> fetchAllCids() {
        synchronized (lock) {
            return new ArrayList<>(userSessions.keySet());
        }
    }

    @Override
    public List<Session> findSession(String cid) {
        synchronized (lock) {
            return userSessions.get(cid);
        }
    }

    @Override
    public List<Session> findAllSessions() {
        synchronized (lock) {
            return userSessions.values()
                    .stream()
                    .flatMap(Collection::stream)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public void removeSession(Session session) {
        String cid = session.getAttribute(CID);
        log.info("从session中获取的cid为:[{}]", cid);

        synchronized (lock) {
            if (userSessions.containsKey(cid)) {
                userSessions.get(cid).remove(session);
            }
        }
    }
}